package org.jeecg.modules.manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiBusinessBank;
import org.jeecg.modules.manage.entity.CaishuiBusinessUser;
import org.jeecg.modules.manage.service.*;
import org.jeecg.modules.manage.vo.CaishuiBusinessPage;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Description: 商户基本信息表[管理]
 * @Author: yfkj
 * @Date:   2023-02-07
 * @Version: V1.0
 */
@Api(tags="商户基本信息表[管理]")
@RestController
@RequestMapping("/manageApi/caishuiBusiness")
@Slf4j
public class MCaishuiBusinessController {
	
	@Autowired
	private IMCaishuiBusinessService imCaishuiBusinessService;
	@Autowired
	private IMCaishuiBusinessUserService imCaishuiBusinessUserService;
	@Autowired
	private IMCaishuiBusinessBankService imCaishuiBusinessBankService;
	@Autowired
	private IMCaishuiServiceCompanyService imCaishuiServiceCompanyService;
	@Resource
	private IMCaishuiCompanySetService imCaishuiCompanySetService;

	//========================================商户基本信息=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusiness
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[管理]-分页列表查询", notes="普通商户基本信息[管理]-分页列表查询")
	@GetMapping(value = "/rootList")
	public Result<IPage<CaishuiBusiness>> queryPageList(CaishuiBusiness caishuiBusiness,
														@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														HttpServletRequest req) {
		String hasQuery = req.getParameter("hasQuery");
		if(hasQuery != null && "true".equals(hasQuery)){
			QueryWrapper<CaishuiBusiness> queryWrapper =  QueryGenerator.initQueryWrapper(caishuiBusiness, req.getParameterMap());
			List<CaishuiBusiness> list = imCaishuiBusinessService.queryTreeListNoPage(queryWrapper);
			IPage<CaishuiBusiness> pageList = new Page<>(1, 10, list.size());
			pageList.setRecords(list);
			return Result.OK(pageList);
		}else{
			String parentId = caishuiBusiness.getPid();
			if (oConvertUtils.isEmpty(parentId)) {
				parentId = "0";
			}
			caishuiBusiness.setPid(null);
			QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, req.getParameterMap());
			// 使用 eq 防止模糊查询
			queryWrapper.eq("pid", parentId);
			Page<CaishuiBusiness> page = new Page<CaishuiBusiness>(pageNo, pageSize);
			IPage<CaishuiBusiness> pageList = imCaishuiBusinessService.page(page, queryWrapper);
			return Result.OK(pageList);
		}
	}

	/**
	 * 【vue3专用】加载节点的子数据
	 *
	 * @param pid
	 * @return
	 */
	@RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
	public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
		Result<List<SelectTreeModel>> result = new Result<>();
		try {
			List<SelectTreeModel> ls = imCaishuiBusinessService.queryListByPid(pid);
			result.setResult(ls);
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 【vue3专用】加载一级节点/如果是同步 则所有数据
	 *
	 * @param async
	 * @param pcode
	 * @return
	 */
	@RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
		Result<List<SelectTreeModel>> result = new Result<>();
		try {
			List<SelectTreeModel> ls = imCaishuiBusinessService.queryListByCode(pcode);
			if (!async) {
				loadAllChildren(ls);
			}
			result.setResult(ls);
			result.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 【vue3专用】递归求子节点 同步加载用到
	 *
	 * @param ls
	 */
	private void loadAllChildren(List<SelectTreeModel> ls) {
		for (SelectTreeModel tsm : ls) {
			List<SelectTreeModel> temp = imCaishuiBusinessService.queryListByPid(tsm.getKey());
			if (temp != null && temp.size() > 0) {
				tsm.setChildren(temp);
				loadAllChildren(temp);
			}
		}
	}

	/**
	 * 获取子数据
	 * @param caishuiBusiness
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[管理]-获取子数据", notes="普通商户基本信息[管理]-获取子数据")
	@GetMapping(value = "/childList")
	public Result<IPage<CaishuiBusiness>> queryPageList(CaishuiBusiness caishuiBusiness,HttpServletRequest req) {
		QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, req.getParameterMap());
		List<CaishuiBusiness> list = imCaishuiBusinessService.list(queryWrapper);
		IPage<CaishuiBusiness> pageList = new Page<>(1, 10, list.size());
		pageList.setRecords(list);
		return Result.OK(pageList);
	}

	/**
	 * 批量查询子节点
	 * @param parentIds 父ID（多个采用半角逗号分割）
	 * @return 返回 IPage
	 * @param parentIds
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[管理]-批量获取子数据", notes="普通商户基本信息[管理]-批量获取子数据")
	@GetMapping("/getChildListBatch")
	public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
		try {
			QueryWrapper<CaishuiBusiness> queryWrapper = new QueryWrapper<>();
			List<String> parentIdList = Arrays.asList(parentIds.split(","));
			queryWrapper.in("pid", parentIdList);
			List<CaishuiBusiness> list = imCaishuiBusinessService.list(queryWrapper);
			IPage<CaishuiBusiness> pageList = new Page<>(1, 10, list.size());
			pageList.setRecords(list);
			return Result.OK(pageList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("批量查询子节点失败：" + e.getMessage());
		}
	}

	/**
	 *   添加
	 *
	 * @param caishuiBusiness
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[管理]-添加")
	@ApiOperation(value="普通商户基本信息[管理]-添加", notes="普通商户基本信息[管理]-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CaishuiBusiness caishuiBusiness) {
		caishuiBusiness.setType(1);
		imCaishuiBusinessService.addCaishuiBusiness(caishuiBusiness);
		return Result.OK("添加成功！",caishuiBusiness.getId());
	}

	/**
	 *  编辑
	 *
	 * @param caishuiBusiness
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[管理]-编辑", dataType = 2)
	@ApiOperation(value="普通商户基本信息[管理]-编辑", notes="普通商户基本信息[管理]-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CaishuiBusiness caishuiBusiness) {
		imCaishuiBusinessService.updateCaishuiBusiness(caishuiBusiness);
		return Result.OK("编辑成功!",caishuiBusiness.getId());
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "普通商户基本信息[管理]-通过id删除")
	@ApiOperation(value="普通商户基本信息[管理]-通过id删除", notes="普通商户基本信息[管理]-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		imCaishuiBusinessService.deleteCaishuiBusiness(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param caishuiBusiness
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, CaishuiBusiness caishuiBusiness) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<CaishuiBusiness> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusiness, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//配置选中数据查询条件
		String selections = request.getParameter("selections");
		if(oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id",selectionList);
		}
		//Step.2 获取导出数据
		List<CaishuiBusiness> caishuiBusinessList = imCaishuiBusinessService.list(queryWrapper);

		// Step.3 组装pageList
		List<CaishuiBusinessPage> pageList = new ArrayList<CaishuiBusinessPage>();
		for (CaishuiBusiness main : caishuiBusinessList) {
			CaishuiBusinessPage vo = new CaishuiBusinessPage();
			BeanUtils.copyProperties(main, vo);
			List<CaishuiBusinessUser> caishuiBusinessUserList = imCaishuiBusinessUserService.selectByMainId(main.getId());
			vo.setCaishuiBusinessUserList(caishuiBusinessUserList);
			List<CaishuiBusinessBank> caishuiBusinessBankList = imCaishuiBusinessBankService.selectByMainId(main.getId());
			vo.setCaishuiBusinessBankList(caishuiBusinessBankList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "商户信息列表");
		mv.addObject(NormalExcelConstants.CLASS, CaishuiBusinessPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商户信息数据", "导出人："+sysUser.getRealname(), "商户信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}
	//========================================商户基本信息=========================================

    //========================================商户银行账户=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusinessBank
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[管理]-分页列表查询银行账户", notes="普通商户基本信息[管理]-分页列表查询银行账户")
	@GetMapping(value = "/bankList")
	public Result<IPage<CaishuiBusinessBank>> queryPageBankList(CaishuiBusinessBank caishuiBusinessBank,
															@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															HttpServletRequest req) {
		QueryWrapper<CaishuiBusinessBank> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusinessBank, req.getParameterMap());
		Page<CaishuiBusinessBank> page = new Page<CaishuiBusinessBank>(pageNo, pageSize);
		IPage<CaishuiBusinessBank> pageList = imCaishuiBusinessBankService.page(page, queryWrapper);
		if(oConvertUtils.listIsNotEmpty(pageList.getRecords())){
			for (CaishuiBusinessBank record : pageList.getRecords()) {
				//根据账号查询服务公司设置相关信息
				BankSetDTO bankSetDTO = imCaishuiCompanySetService.queryCompanySet(record.getMainAccount());
				//查询记账子单元余额
				Result result = CMBApi.querySubUnitBalance(record.getMainAccount(),record.getSubAccountId(), bankSetDTO);
				if(result.isSuccess()){
					record.setBalance(BigDecimal.valueOf(oConvertUtils.getDouble(result.getResult()+"",0.00)));
				}
			}
		}
		return Result.OK(pageList);
	}
    //========================================商户银行账户=========================================

	//========================================商户用户信息=========================================
	/**
	 * 分页列表查询
	 *
	 * @param caishuiBusinessUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="普通商户基本信息[管理]-分页列表查询用户信息", notes="普通商户基本信息[管理]-分页列表查询用户信息")
	@GetMapping(value = "/userList")
	public Result<IPage<CaishuiBusinessUser>> queryPageUserList(CaishuiBusinessUser caishuiBusinessUser,
															@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															HttpServletRequest req) {
		QueryWrapper<CaishuiBusinessUser> queryWrapper = QueryGenerator.initQueryWrapper(caishuiBusinessUser, req.getParameterMap());
		Page<CaishuiBusinessUser> page = new Page<CaishuiBusinessUser>(pageNo, pageSize);
		IPage<CaishuiBusinessUser> pageList = imCaishuiBusinessUserService.pageMultiTable(page, queryWrapper);
		return Result.OK(pageList);
	}
	//========================================商户用户信息=========================================
	
}
